package com.msr.interceptors;

import com.msr.utils.JwtUtil;
import com.msr.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/**
 * @author tom
 * @version V1.0
 * @Package com.msr.interceptors
 * @date 2025/1/23 10:09
 * @Copyright © 株式会社多言语系统研究所
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //通过请求头获取令牌
        String token = request.getHeader("Authorization");
        //验证令牌
        try {
            //如果代码能执行到此处，则说明验证是成功的
            Map<String, Object> claims =  JwtUtil.parseToken(token);
            //保存登录令牌
            ThreadLocalUtil.set(claims);

            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            String redisToken = operations.get(token);

            if(redisToken==null){ //如果redis中token是null，则认为是没有访问权限
                //手动抛出异常
                throw new RuntimeException();
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(401); //权限不足
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //释放资源
        ThreadLocalUtil.remove();
    }
}
